// Package sales @Title sales[简述该包的主要作用]
// @Description
// @Author  cnHuaShao
// @since v0.0.1
// @Version v1.0.0
// @Date 2024/5/24 17:21
// @Update 2024/5/24 17:21
package sales

import (
	"FinancialManagement/src/base/baselog"
	"FinancialManagement/src/base/db"
	"fmt"
	"go.uber.org/zap"
)

// deleteSalesDetail
// @Description: 删除指定销售单，逻辑删除
// @receiver salesDetail
// @return err
func (salesDetail *SalesDetail) deleteSalesDetail() (err error) {
	err = db.Res.DB.GetDbW().Model(salesDetail).Where("sales_id", salesDetail.SalesID).Update("sales_status", 3).Error
	return err
}

// updateSalesDetailItem
// @Description:  更新销售明细条目
// @receiver salesDetailItem
// @return error
func (salesDetailItem *SalesDetailItem) updateSalesDetailItem() error {
	err := db.Res.DB.GetDbW().Save(salesDetailItem).Error
	return err
}

// GetSalesDetailItem
// @Description: 依据销售明细ID进行获取销售明细条目
// @receiver sdi
// @return error
func (salesDetailItem *SalesDetailItem) GetSalesDetailItem() error {
	return db.Res.DB.GetDbR().Where("sdi_id=?", salesDetailItem.SdiID).First(salesDetailItem).Error
}

// getSalesDetailInfo
// @Description: 只获取销售订单
// @param salesId
// @return salesDetail
// @return err
func getSalesDetailInfo(salesId int) (salesDetail SalesDetail, err error) {
	err = db.Res.DB.GetDbR().Where("sales_id=?", salesId).First(&salesDetail).Error
	return salesDetail, err
}

// GetSalesDetailInfoAndItems
// @Description: 获取指定销售单和其具体明细信息
// @param salesId
// @return salesDetail
// @return err
func GetSalesDetailInfoAndItems(salesId int) (salesDetail SalesDetail, err error) {
	// 获取销售单
	sql := fmt.Sprintf("SELECT sd.sales_id, sd.sales_type, sd.sales_total_price, sd.sales_actual_total_price, sd.sales_pure_profit, sd.sales_remarks, sd.sales_status, sd.sales_person, sd.sales_createtime, sd.purchase_id,(SELECT CONCAT(purchase_vehicle,'/',purchase_departuredate) as purchaseName FROM purchase_detail pd WHERE pd.purchase_id=sd.purchase_id) FROM sales_detail AS sd where sales_id=%d", salesId)
	res := db.Res.DB.GetDbR().Raw(sql).Row()
	if res.Err() != nil {
		return salesDetail, res.Err()
	}
	err = res.Scan(&salesDetail.SalesID, &salesDetail.SalesType, &salesDetail.SalesTotalPrice, &salesDetail.SalesActualTotalPrice, &salesDetail.SalesPureProfit, &salesDetail.SalesRemarks, &salesDetail.SalesStatus, &salesDetail.SalesPerson, &salesDetail.SalesCreateTime, &salesDetail.PurchaseId, &salesDetail.PurchaseName)
	if err != nil {
		baselog.Logger.Error("解析错误", zap.Error(err))
		return salesDetail, err
	}
	// 获取销售明细
	sqlItems := fmt.Sprintf("SELECT sdi.sdi_id, sdi.sales_id, sdi.product_id,(SELECT pd.product_name FROM product pd WHERE pd.product_id=sdi.product_id) as productName, sdi.sdi_quantity, sdi.sdi_price, sdi.total_price, sdi.sdi_actual_amount, sdi.sdi_cost_unit_price, sdi.sdi_full_cost_price, sdi.sdi_pure_profit, sdi.customer_id,(SELECT ct.name FROM customer ct WHERE ct.customer_id=sdi.customer_id) as customerName, sdi.sdi_date FROM sales_detail_item AS sdi WHERE sdi.sales_id =%d", salesId)
    ress, err := db.Res.DB.GetDbR().Raw(sqlItems).Rows()
    if err != nil {
        baselog.Logger.Error("解析错误", zap.Error(err))
        return salesDetail, err
    }
    defer ress.Close()
    for ress.Next() {
        var sdi SalesDetailItem
        err = ress.Scan(&sdi.SdiID, &sdi.SalesID, &sdi.ProductID, &sdi.ProductName, &sdi.SdiQuantity, &sdi.SdiPrice, &sdi.TotalPrice, &sdi.SdiActualAmount, &sdi.SdiCostUnitPrice, &sdi.SdiFullCostPrice, &sdi.SdiPureProfit, &sdi.CustomerID, &sdi.CustomerName, &sdi.SdiDate)
        if err != nil {
            baselog.Logger.Error("解析错误", zap.Error(err))
        }
        salesDetail.Items = append(salesDetail.Items, sdi)
    }
	return salesDetail, err
}

// GetSalesDetailList
// @Description: 获取销售明细列表
// @param pageSize
// @param pageNumber
// @return salesDetailList
// @return count
// @return err
func (sd *SalesDetail) GetSalesDetailList(pageSize, pageNumber int) (salesDetailList []SalesDetail, count int64, err error) {
	// 计算起始行
	startPage := (pageNumber - 1) * pageSize
	sqlWhere := " sd.sales_status !=3 "
	if sd.SalesID != 0 {
		sqlWhere += fmt.Sprintf(" AND sd.sales_id=%d ", sd.SalesID)
	}
	sql := fmt.Sprintf("SELECT sd.sales_id, sd.sales_type, sd.sales_total_price, sd.sales_actual_total_price, sd.sales_pure_profit, sd.sales_remarks, sd.sales_status, sd.sales_person, sd.sales_createtime, sd.purchase_id,(SELECT CONCAT(purchase_vehicle,'/',purchase_departuredate) as purchaseName FROM purchase_detail pd WHERE pd.purchase_id=sd.purchase_id) FROM sales_detail AS sd WHERE %s  order by sd.sales_id desc limit %d offset %d",
		sqlWhere, pageSize, startPage)
    res, err := db.Res.DB.GetDbR().Raw(sql).Rows()
    if err != nil {
        return nil, 0, err
    }
    defer res.Close()
    for res.Next() {
        var salesDetail SalesDetail
        err = res.Scan(&salesDetail.SalesID, &salesDetail.SalesType, &salesDetail.SalesTotalPrice, &salesDetail.SalesActualTotalPrice, &salesDetail.SalesPureProfit, &salesDetail.SalesRemarks, &salesDetail.SalesStatus, &salesDetail.SalesPerson, &salesDetail.SalesCreateTime, &salesDetail.PurchaseId, &salesDetail.PurchaseName)
        if err != nil {
            baselog.Logger.Error("解析错误", zap.Error(err))
        }
        salesDetailList = append(salesDetailList, salesDetail)
    }
	sqlCount := fmt.Sprintf("select count(*) from sales_detail AS sd WHERE %s ", sqlWhere)
	err = db.Res.DB.GetDbR().Raw(sqlCount).Scan(&count).Error
	return salesDetailList, count, err
}

// createSalesDetail
// @Description: 创建销售明细
// @param salesDetail
// @return err
func (salesDetail *SalesDetail) createSalesDetail() (err error) {
	result := db.Res.DB.GetDbW().Create(salesDetail)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

// UpdateSalesDetail
//
//	@Description: 修改指定销售单信息
//	@receiver salesDetail
//	@return error
func (salesDetail *SalesDetail) UpdateSalesDetail() error {
	err := db.Res.DB.GetDbW().Save(salesDetail).Error
	return err
}

// DeleteSalesDetailItem
// @Description: 删除指定销售单明细信息
// @receiver salesDetailItem
// @return error
func (salesDetailItem *SalesDetailItem) DeleteSalesDetailItem() error {
	err := db.Res.DB.GetDbW().Delete(salesDetailItem).Error
	return err
}

// createSalesDetailItem
//
//	@Description: 创建销售明细条目
//	@receiver salesDetailItem
//	@return err
func (salesDetailItem *SalesDetailItem) createSalesDetailItem() (err error) {
	err = db.Res.DB.GetDbW().Create(salesDetailItem).Error
	return err
}
